package com.atguigu.realtime.util

import java.sql._

/**
 * Author atguigu
 * Date 2020/11/24 10:11
 */
object JDBCUtil {
 
    // "select .. from t where id=? and name=?"
    def query(url: String,
              sql: String,
              args: List[Object]): List[Map[String, Object]] = {
        // 1. 获取到数据库的连接
        val conn: Connection = DriverManager.getConnection(url)
        // 2. 使用连接得到一个 PrepareStatement
        val ps: PreparedStatement = conn.prepareStatement(sql)
        
        // 3. 替换占位符
        args.zipWithIndex.foreach {
            case (arg, i) =>
                ps.setObject(i + 1, arg)
        }
        // 4. 执行查询
        val resultSet: ResultSet = ps.executeQuery()
        // 5. 解析查询结果
        var result = List[Map[String, Object]]()
        val metaData: ResultSetMetaData = resultSet.getMetaData
        while (resultSet.next()) {
            var map = Map[String, Object]()
            for (i <- 1 to metaData.getColumnCount) {
                val key: String = metaData.getColumnName(i)
                val value: Object = resultSet.getObject(i)
                map += key -> value
            }
            result :+= map
        }
        ps.close()
        conn.close()
        
        result
        
    }
}

/*

多行
    List[Map[..], Map[...], ...]
每行多列
    Map[列->值, 列-> 值, ...]



(1 to args.length).foreach(i => {
            ps.setObject(i, args(i - 1))
        })
 */